package cn.lyyb2001.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.lyyb2001.blog.entity.Article;
import cn.lyyb2001.blog.entity.Category;
import cn.lyyb2001.blog.mapper.ArticleMapper;
import cn.lyyb2001.blog.mapper.CategoryMapper;
import cn.lyyb2001.blog.service.IArticleService;
import cn.lyyb2001.blog.vo.ArticleVO;
import cn.lyyb2001.common.utils.RedisUtil;
import cn.lyyb2001.common.web.util.JwtUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author daiyb2
 * @Title: ArticleServiceImpl
 * @Description:
 * @date 2021/11/20 22:54
 **/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements IArticleService {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private RedisUtil redisUtil;
    public static final String LIKE_ARTICLES = "like_articles";

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateArticle(ArticleVO articleVO) {
        Article article = BeanUtil.toBean(articleVO, Article.class);
        article.setUserId(JwtUtils.getUserId());
        //不是存为草稿
        if (articleVO.getStatus() != 3){
            // 保存文章分类
            Category category = saveArticleCategory(articleVO);
            // 保存或修改文章
            if (ObjectUtil.isNotNull(category)) {
                article.setCategoryId(category.getId());
            }
        }
        saveOrUpdate(article);
        if(article.getStatus()!=3){
            // 保存文章标签
            saveArticleTag(articleVO, article.getId());
        }
    }

    @Override
    public ArticleVO getArticleVO(Integer id) {
        Article article = baseMapper.selectById(id);
        ArticleVO articleVO = BeanUtil.toBean(article,ArticleVO.class);
        articleVO.setCategoryName(categoryMapper.selectById(article.getCategoryId()).getCategoryName());
        String ipAddress = ServletUtil.getClientIP(request);
        String md5 = DigestUtils.md5DigestAsHex((id+ipAddress).getBytes());
        if(redisUtil.sHasKey("ACCESS", md5)){
            articleVO.setViewsCount(articleVO.getViewsCount()+1);
            redisUtil.sSetAndTime("ACCESS",30,md5);
            baseMapper.update(null,new LambdaUpdateWrapper<Article>().set(Article::getViewsCount,article.getViewsCount()).eq(Article::getId,id));
        }
        return articleVO;
    }

    @Override
    public IPage<ArticleVO> list(Page<ArticleVO> page, ArticleVO articleVO) {
        List<ArticleVO> list = baseMapper.list(page, articleVO);
        page.setRecords(list);
        return page;
    }

    @Override
    public int like(Integer id) {
        // 获取ip
//        UserAgent userAgent = UserAgentUtil.parse(request.getHeader("user-agent"));
//        String ipAddress = ServletUtil.getClientIP(request);
        // 获取访问设备
//        Browser browser = userAgent.getBrowser();
//        String name= userAgent.getPlatform().getName();
//        String uuid =  browser.getName() + name;
//        String md5 = DigestUtils.md5DigestAsHex(uuid.getBytes());
        Article article = baseMapper.selectById(id);
        baseMapper.update(null,new LambdaUpdateWrapper<Article>().
                set(Article::getLikeCount,article.getLikeCount()+1).
                eq(Article::getId,id));
        return 0;
    }


    /**
     * 保存文章分类
     * @param articleVO
     * @return
     */
    private Category saveArticleCategory(ArticleVO articleVO) {
        // 判断分类是否存在
        Category category = categoryMapper.selectOne(new LambdaQueryWrapper<Category>()
                .eq(Category::getCategoryName, articleVO.getCategoryName()));
        if (ObjectUtil.isNull(category)) {
            category = new Category();
            category.setCategoryName(articleVO.getCategoryName());
            categoryMapper.insert(category);
        }
        return category;
    }

    /**
     * 保存文章标签
     * @param articleVO
     * @param articleId
     */
    private void saveArticleTag(ArticleVO articleVO, Integer articleId) {
        // 编辑文章则删除文章所有标签
        if (ObjectUtil.isNotNull(articleVO.getId())) {
//            articleTagDao.delete(new LambdaQueryWrapper<ArticleTag>()
//                    .eq(ArticleTag::getArticleId, articleVO.getId()));
        }
        // 添加文章标签
//        List<String> tagNameList = articleVO.getTagNameList();
//        if (CollectionUtils.isNotEmpty(tagNameList)) {
//            // 查询已存在的标签
//            List<Tag> existTagList = tagService.list(new LambdaQueryWrapper<Tag>()
//                    .in(Tag::getTagName, tagNameList));
//            List<String> existTagNameList = existTagList.stream()
//                    .map(Tag::getTagName)
//                    .collect(Collectors.toList());
//            List<Integer> existTagIdList = existTagList.stream()
//                    .map(Tag::getId)
//                    .collect(Collectors.toList());
//            // 对比新增不存在的标签
//            tagNameList.removeAll(existTagNameList);
//            if (CollectionUtils.isNotEmpty(tagNameList)) {
//                List<Tag> tagList = tagNameList.stream().map(item -> Tag.builder()
//                        .tagName(item)
//                        .build())
//                        .collect(Collectors.toList());
//                tagService.saveBatch(tagList);
//                List<Integer> tagIdList = tagList.stream()
//                        .map(Tag::getId)
//                        .collect(Collectors.toList());
//                existTagIdList.addAll(tagIdList);
//            }
//            // 提取标签id绑定文章
//            List<ArticleTag> articleTagList = existTagIdList.stream().map(item -> ArticleTag.builder()
//                    .articleId(articleId)
//                    .tagId(item)
//                    .build())
//                    .collect(Collectors.toList());
//            articleTagService.saveBatch(articleTagList);
//        }
    }
}
